<template>
  <el-form
    ref="loginForm"
    :model="form"
    :rules="rules"
    label-width="0"
    size="large"
    @keyup.enter="login"
  >
    <el-form-item prop="user">
      <el-input
        v-model="form.user"
        prefix-icon="el-icon-user"
        clearable
        :placeholder="$t('login.userPlaceholder')"
      >
        <template #append>
          <el-select v-model="userType" style="width: 130px">
            <el-option :label="$t('login.admin')" value="admin"></el-option>
            <el-option :label="$t('login.user')" value="user"></el-option>
          </el-select>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="form.password"
        prefix-icon="el-icon-lock"
        clearable
        autocomplete="new-password"
        show-password
        :placeholder="$t('login.PWPlaceholder')"
      ></el-input>
    </el-form-item>
    <el-form-item style="margin-bottom: 10px">
      <el-col :span="12">
        <el-checkbox
          :label="$t('login.rememberMe')"
          v-model="form.autologin"
        ></el-checkbox>
      </el-col>
      <el-col :span="12" class="login-forgot">
        <router-link to="/reset_password"
          >{{ $t("login.forgetPassword") }}？</router-link
        >
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        style="width: 100%"
        :loading="islogin"
        round
        @click="login"
        >{{ $t("login.signIn") }}</el-button
      >
    </el-form-item>
    <div class="login-reg">
      {{ $t("login.noAccount") }}
      <router-link to="/user_register">{{
        $t("login.createAccount")
      }}</router-link>
    </div>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      userType: "admin",
      form: {
        user: "administrators",
        password: "b3oJWCiN@",
        autologin: false,
      },
      btnRole: [],
      rules: {
        user: [
          {
            required: true,
            message: this.$t("login.userError"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("login.PWError"),
            trigger: "blur",
          },
        ],
      },
      islogin: false,
    };
  },
  watch: {
    userType(val) {
      if (val == "admin") {
        this.form.user = "admin";
        this.form.password = "admin";
      } else if (val == "user") {
        this.form.user = "user";
        this.form.password = "user";
      }
    },
  },
  mounted() {},
  methods: {
    traverseTree(arr) {
      var result = [];
      if (Array.isArray(arr)) {
        arr.forEach((node) => {
          console.log("newNode", node);
          var newNode = { ...node }; // 创建一个新的节点，避免修改原数组

          newNode.name = newNode.cMenuNo;
          newNode.meta = {
            title: newNode.cMenuName,
            icon: newNode.cIcon,
            type: newNode.cAction,
          };
          if (newNode.cParentMenuNo) {
            newNode.component = newNode.cUrl;
            newNode.path = newNode.cPath;
            if (newNode.cAction === "button") {
              this.btnRole.push(newNode.cMenuNo);
            }
          } else {
            newNode.path = newNode.cPath || "system";
          }
          if (newNode.children) {
            newNode.children = this.traverseTree(newNode.children); // 递归遍历子节点
          }
          result.push(newNode); // 将新节点添加到结果数组中
        });
      }
      return result;
    },
    async login() {
      var validate = await this.$refs.loginForm.validate().catch(() => {});
      if (!validate) {
        return false;
      }

      this.islogin = true;
      var data = {
        cAccount: this.form.user,
        cPassword: this.$TOOL.crypto.MD5(this.form.password).toUpperCase(),
      };
      //获取token
      try {
        var user = await this.$API.system.login.Login.post(data);

        this.$TOOL.cookie.set("TOKEN", user.token, {
          expires: this.form.autologin ? 24 * 60 * 60 : 0,
        });
        const res = await this.$API.system.login.GetUserById.get();

        this.$TOOL.data.set("USER_INFO", res.content);
      } catch (error) {
        this.islogin = false;
        // this.$message.warning(error);
        return false;
      }

      //获取菜单
      var menu = null;
      let { content: menuRouters } =
        await this.$API.system.login.GetMenuRole.post();
      // console.log("result", this.traverseTree(menuRouters));

      let arrTest = this.traverseTree(menuRouters);

      arrTest = [
        {
          name: "home",
          path: "/home",
          meta: {
            title: "首页",
            icon: "el-icon-eleme-filled",
            type: "menu",
          },
          children: [
            {
              path: "/system/setting/table",
              name: "tableSetting",
              meta: {
                title: "表格列管理",
                icon: "el-icon-scale-to-original",
                type: "menu",
              },
              component: "system/setting/table",
            },
            {
              path: "/system/vab/table/column",
              name: "tableCustomColumn",
              meta: {
                title: "用户列表动态测试",
                icon: "el-icon-scale-to-original",
                type: "menu",
              },
              component: "system/vab/table/column",
            },
            {
              name: "dashboard",
              path: "/dashboard",
              meta: {
                title: "控制台",
                icon: "el-icon-menu",
                affix: true,
              },
              component: "home",
            },
            {
              name: "userCenter",
              path: "/usercenter",
              meta: {
                title: "帐号信息",
                icon: "el-icon-user",
                tag: "NEW",
              },
              component: "userCenter",
            },
            // {
            //   name: "settingMenu",
            //   path: "/system/menu",
            //   meta: {
            //     title: "菜单",
            //     icon: "el-icon-user",
            //   },
            //   component: "settingMenu",
            // },
          ],
        },
        ...arrTest,
      ];

      this.$TOOL.data.set("MENU", arrTest);
      console.log(this.btnRole);
      this.$TOOL.data.set("PERMISSIONS", this.btnRole);
      // if (this.form.user == "admin") {
      //   menu = await this.$API.system.menu.myMenus.get();
      // } else {
      //   menu = await this.$API.demo.menu.get();
      // }
      // if (menu.code == 200) {
      //   if (menu.data.menu.length == 0) {
      //     this.islogin = false;
      //     this.$alert(
      //       "当前用户无任何菜单权限，请联系系统管理员",
      //       "无权限访问",
      //       {
      //         type: "error",
      //         center: true,
      //       }
      //     );
      //     return false;
      //   }
      //   this.$TOOL.data.set("MENU", menu.data.menu);
      //   this.$TOOL.data.set("PERMISSIONS", menu.data.permissions);
      //   this.$TOOL.data.set("DASHBOARDGRID", menu.data.dashboardGrid);
      // } else {
      //   this.islogin = false;
      //   this.$message.warning(menu.message);
      //   return false;
      // }

      this.$router.replace({
        path: "/",
      });
      this.$message.success("Login Success 登录成功");
      this.islogin = false;
    },
  },
};
</script>

<style></style>
